package com.guigu.tms.geteway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guigu.tms.geteway.entity.Result;
import com.guigu.tms.geteway.feign.CustomerAuthFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class CustomerAuthFilter implements GlobalFilter, Ordered {
    
    @Autowired
    private CustomerAuthFeignClient customerAuthFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path=request.getPath().toString();
        System.out.println("路径：" + path);
        if(path.contains("/customer")) {
            ServerHttpResponse response = exchange.getResponse();
            Result result = customerAuthFeignClient.checkAuth(request.getHeaders().getFirst("auth"));

            ObjectMapper objectMapper = new ObjectMapper();
            String res="";
            try {
                res=objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            if(Integer.parseInt(result.get("code").toString())==1){
                return chain.filter(exchange);
            }

            DataBuffer buffer = response.bufferFactory().wrap(res.getBytes());
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));


        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
